<template>
	<div>
		<input type="text" v-model="user.username" />
		<input type="text" v-model="user.password" />
		<button @click="handleLogin">登录</button>
	</div>
</template>

<script lang="ts">
import { reactive, defineComponent } from "vue";
import { IUser } from '@/typings'
import { fetchLogin } from '@/api'
import { useRouter } from "vue-router";
import { useStore } from 'vuex'

export default defineComponent({
	setup() {
		const router = useRouter()
		const store = useStore()
		const user = reactive<IUser>({
			username: '',
			password: ''
		})

		// 处理登录逻辑函数
		const handleLogin = async () => {
			// 请求登录
			const resp = await fetchLogin(user)
			// 获取请求回来的code token role
			const { code, token, role } = resp.data
			// 验证code 
			if (code === 200) {
				// 保存token到本地
				localStorage.setItem('token', token)
				// 存储角色
				localStorage.setItem('role', role)
				// 设置vuex上的动态路由
				store.dispatch('set_dynamicRouter', role).then(() => {
					// 跳转页面
					router.push({ path: '/home' })
				})

			} else {
				alert('账户密码错误!')
			}
		}

		return {
			user,
			handleLogin
		}
	},
})
</script>